package com.dd.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.struts.upload.FormFile;

public class UpFile {

	public String uploadfile(String path, FormFile file, String imageid) {
		if (file == null) {
			return path;
		}
		String filetype = file.getFileName().substring(
				file.getFileName().lastIndexOf("."),
				file.getFileName().length());
		String filename = imageid + filetype;
		int filesize = file.getFileSize();
		if (filesize == 0) {
			return "";
		}
		try {
			// 得到文件的输入流
			InputStream is = file.getInputStream();
			// 上传文件
			File file1 = new File(path);
			file1.delete();
			new File(path).createNewFile(); // 创建路径
			uploadFile(is, path);
		} catch (IOException ex) {
			ex.printStackTrace();
			return "";
			// 假如上传文件失败，设置一个失败的标记位
		}
		return filename;
	}

	/**
	 * �ϴ��ļ�
	 * 
	 * @param fileName
	 * @param is
	 * @throws IOException
	 */
	private void uploadFile(InputStream is, String path) throws IOException {
		OutputStream os = new FileOutputStream(new File(path));
		// 8k�������
		byte[] buffer = new byte[1024 * 8];
		// ���ö}����ֽ���
		int len;
		while ((len = is.read(buffer)) != -1) {
			// ���������д�����
			os.write(buffer, 0, len);
		}
		// �ر������
		os.close();
		// �ر�������
		is.close();
	}

}
